package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {

    @Autowired
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryWithPassThrough(String keyPreFix, ID id, Class<R> type, Function<ID, R> dbFallback
            , Long time, TimeUnit unit) {
        String key = keyPreFix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        } else if (json != null) {
            //解决缓存穿透
            return null;
        }
        R r = dbFallback.apply(id);
        if (r == null) {
            //解决缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key, r, time, unit);
        return r;
    }


    //设置线程池
    private final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //缓存击穿_逻辑过期
    public <R, ID> R queryWithLogicalExpire(String keyPerfix, ID id, Class<R> type, Function<ID, R> dbFallback
            , Long time, TimeUnit unit) throws InterruptedException {
        String key = keyPerfix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        RedisData data = JSONUtil.toBean(json, RedisData.class);
        JSONObject jsonObject = (JSONObject) data.getData();
        R r = JSONUtil.toBean(jsonObject, type);
        LocalDateTime expireTime = data.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            //doubleCheck redis缓存
            /*
              因为可能出现最后已经更新完毕了，但是一个线程还是走到了获取锁的操作，
            就导致还要再次 执行 saveShopToRedis(id, 20L); 一次 ，但是实际已经不需要了
            所以这里再次check一下缓存，看是不是最新的数据，如果是就返回它
            */
                json = stringRedisTemplate.opsForValue().get(key);
                data = JSONUtil.toBean(json, RedisData.class);
                jsonObject = (JSONObject) data.getData();
                r = JSONUtil.toBean(jsonObject, type);
                expireTime = data.getExpireTime();
                if (expireTime.isAfter(LocalDateTime.now())) {
                    unLock(lockKey);
                    return r;
                }
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r1 = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        return r;
    }

    private boolean tryLock(String key) {
        Boolean flage = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flage);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

}